﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utils.Helpers;

namespace Utils.JqGrid
{
    [ModelBinder(typeof(GridModelBinder))]
    public class GridSettings
    {
        public bool IsSearch { get; set; }
        public int PageSize { get; set; }
        public int PageIndex { get; set; }
        public string SortColumn { get; set; }
        public string SortOrder { get; set; }

        public Filter Where { get; set; }

        public IQueryable<T> SearchAndSort<T>(IQueryable<T> query)
        {
            //filtring
            if (IsSearch)
            {
                //And
                if (Where.groupOp == "AND")
                    foreach (var rule in Where.rules)
                        query = query.Where<T>(
                            rule.field, rule.data,
                            (WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op));
                else
                {
                    //Or
                    var temp = (new List<T>()).AsQueryable();
                    foreach (var rule in Where.rules)
                    {
                        var t = query.Where<T>(
                        rule.field, rule.data,
                        (WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op));
                        temp = temp.Concat<T>(t);
                    }
                    //remove repeating records
                    query = temp.Distinct<T>();
                }
            }

            //sorting
            query = query.OrderBy<T>(SortColumn,
                SortOrder);

            return query;
        }
    }
}